<template>
	<div class="container" >
		<div class="form-box" v-if="fistDis">
			<el-form ref="productFormRef" :rules="productFormRules" :model="productForm" :label-width="formLabelWidth">
				<el-form-item label="ID" v-if="false">
					<el-input v-model="productForm.id" placeholder="ID" clearable size="medium" style="width:350px"/>
				</el-form-item>
				<el-form-item label="所属品牌" prop="productBoardId">
					<el-input v-model="productForm.productBoardId"  v-if="false"/>
					<el-input v-model="productForm.productBoardName" placeholder="选择品牌" clearable readonly size="medium" style="width:350px" @click="func_loadvBoardsDict()"/>
				</el-form-item>
				<el-form-item label="商品货号（批号）" prop="productSno">
					<el-input v-model="productForm.productSno" placeholder="商品货号（批号）" clearable size="medium" style="width:350px"/>
				</el-form-item>
				<el-form-item label="商品名称" prop="productName">
					<el-input v-model="productForm.productName" placeholder="商品名称" clearable size="medium" style="width:350px"/>
				</el-form-item>
				<el-form-item label="是否包邮" prop="shipmentType">
					<el-switch v-model="productForm.shipmentType" class="handle-switch mr40"
					placeholder="是否包邮"
					:active-value= "1" :inactive-value= "0"
					active-color="#13ce66" inactive-color="#ff4949" />
				</el-form-item>
				<el-form-item label="邮费" prop="shipmentPrice">
					<el-input v-model="productForm.shipmentPrice" placeholder="邮费" clearable size="medium" style="width:350px" align="right" />
				</el-form-item>
				<el-form-item label="发货省份" prop="shipmentProvince">
					<el-input v-model="productForm.shipmentProvince" placeholder="发货省份" clearable size="medium" style="width:350px" />
					<el-cascader v-model="provinceOptionVal"
						@focus="func_loadShipmentProvinceOptions" @change="func_setShipmentProvince"
						:options="shipmentProvinceOptions" :props="provinceOptionProps" placeholder="发货省份" clearable size="medium" style="width:350px" />
				</el-form-item>
				<el-form-item label="价格" prop="price">
					<el-input v-model="productForm.price" placeholder="价格" clearable size="medium" style="width:350px" align="right" />
				</el-form-item>
				<el-form-item label="积分兑换值" prop="points">
					<el-input v-model="productForm.points" placeholder="积分兑换值" clearable size="medium" style="width:350px" align="right" />
				</el-form-item>
				<el-form-item label="概要描述（100字以内）" prop="productDescribe">
					<el-input type="textarea" style="width:350px" maxlength="110" show-word-limit
					:autosize="{ minRows: 10, maxRows: 12}" v-model="productForm.productDescribe" placeholder="项目描述">
					</el-input>
				</el-form-item>
				<el-form-item label="商品展示主图">
					<el-input v-model="productForm.urlPic" placeholder="商品展示主图" v-if="false"/>
					<el-image v-if="masterImageUrl" class="avatar" shape="square" :src="masterImageUrl" />
					<VAvatarUpload v-else v-bind:selectValue="VAvatar" @avatar="func_loadVAvatarData" />
				</el-form-item>
				<el-form-item label="多张展示图">
					<el-upload class="upload-demo"
						action="http://127.0.0.1:4890/portal/admin/file/uploadImage"
						list-type="picture-card"
						:on-preview="func_handleContentPicPreview"
						:on-remove="func_handleContentPicRemove"
						:on-success="func_handleContentPicsSuccess"
						:file-list="fileList"
					>
						<i class="el-icon-plus" ></i>
						<template #tip>
							<div class="el-upload__tip">
								<li>1. 仅支持图片类型文件，包含 jpg/png 格式文件。</li>
								<li>2. 单个文件上传限定 4MB 以内。</li>
							</div>
						</template>
					</el-upload>
					<el-dialog v-model="dialogImageVisible" title="图片预览" :width="dialogImageWidth" center>
						<el-image w-full :src="dialogImageUrl" alt="图片预览" />
						<div style="padding: 14px">
							<span>{{productForm.productDescribe}}</span>
							<div class="bottom">
							<time class="time">{{ productForm.createTime }}</time>
							</div>
						</div>
						<template #footer>
							<span class="dialog-footer"><el-button @click="dialogImageVisible = false" plain>关闭</el-button></span>
						</template>
					</el-dialog>
					<el-input v-model="productForm.contentPics" placeholder="商品多张展示图" v-if="false"/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onNext(2)" plain>下一步</el-button>
					<el-button type="success" @click="onReset" plain>重置数据</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="form-box" v-if="sndDis">
			<el-divider content-position="left">商品多媒体页面编辑</el-divider>
			<el-form :model="productForm" :label-width="formLabelWidth">
				<!-- <el-form-item><span> {{productForm.detailsContent}}</span></el-form-item> -->
				<el-form-item label="商品介绍详情">
					<el-input type="textarea" style="width:550px" maxlength="110" show-word-limit
					:autosize="{ minRows: 10, maxRows: 12}" v-model="productForm.detailsContent" placeholder="商品介绍详情">
					</el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onSubmit" plain>提交</el-button>
					<el-button type="success" @click="onNext(1)" plain>上一步</el-button>
				</el-form-item>
			</el-form>
		</div>
        <el-dialog v-model="vBoardsVisible" append-to-body>
            <VBoards @boardsDictData="func_loadvBoardsDictData" />
        </el-dialog>
	</div>
</template>

<script>
import { onMounted, ref, reactive, toRefs, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from "element-plus";
import {findAttributeListPageByClassifyId, findAttributeListByClassifyId, } from "../../../../api/hairmanager/productAttribute.js"
import { findProductInfoListById, saveProductInfo } from "../../../../api/hairmanager/products";
import { loadProvTrees, } from "../../../../api/dict";

import { NO_DATA_SELECT_ERROR, SUCCESS_ADDDATA_DIALOG_MESSAGE, SUCCESS_DELDATA_DIALOG_MESSAGE, SUCCESS_EDITDATA_DIALOG_MESSAGE, formLabelWidth, } from "../../../../api/CommonErrorMessage.js";

import VBoards from "./boards.vue";
import VAvatarUpload from '../../../../components/AvatarUpload.vue';

export default {
    name: "productForm",
	components: {VBoards, VAvatarUpload },
	props:{
        selectValue: Object,
	},
	emits: ["formData"],
    setup(props, cex){
		onMounted(() => {
		});
        const router = useRouter();
		const route = useRoute();
        const formLabelWidth = ref("170px");
		const fistDis = ref(true);
		const sndDis = ref(false);
		// 商品主图图片
		
        const dialogImageUrl = ref("");
		const dialogImageVisible = ref(false);
		const dialogImageWidth = ref(0);
        const productFormRef = ref(null);
        const productForm = reactive({
			id: 0,
			productSno: "",
			productName: "",
			productDescribe: "",
			points: 0,
			price: 0,
			detailsContent: "",
			urlPic: "",
			contentPics: "",
			contentPicList: [],
			shipmentType: 0,
			shipmentPrice: 0,
			shipmentProvince: "",
			productClassifyId: "",
			productBoardId: 0,
			productBoardName: "",
			createTime: "",
        });
		const attrValueInput = ref([]);
		const productAttributeList = ref([]);
		const productAttributeForm = reactive({
			productSpecParam: [{}],
		});
		const fileList = ref([]);
		// 表单验证规则
        const productFormRules = {
            productName: [
                { required: true, message: "请输入商品名称", trigger: "blur" },
            ],
            shipmentPrice : [
                { required: true, message: "请输入邮费", trigger: "blur" },
            ],
        };
        // =========================================================================================
		const classifyId = ref(0);
		const provinceOptionVal = ref('');
		const shipmentProvinceOptions = ref([]);
        const provinceOptionProps = {
            checkStrictly: true,
        }
		const func_loadShipmentProvinceOptions = () => {
			loadProvTrees().then((res) => {
				shipmentProvinceOptions.value = res.data;
			});
		};
		const func_setShipmentProvince = () => {
			productForm.shipmentProvince = provinceOptionVal.value.join(',');
		};
        // 主业务处理 ========================================================================================= START
		const onNext = (v) => {
			switch(v){
				case 1:
					fistDis.value = true;
					sndDis.value = false;
					cex.emit('formData', {state: 1, data: []});
					attrValueInput.value=[];
					break;
				case 2:
					fistDis.value = false;
					sndDis.value = true;
					cex.emit('formData', {state: 2, data: []});
					func_loadClassifyAttribute();
					break;
				default:
					break;
			}
		};
		const func_loadClassifyAttribute = () => {
			findAttributeListByClassifyId(classifyId.value).then((res) => {
				// productAttributeList.value = res.data;
				res.data.forEach((element) => {
					var obj = { attrId: 0, attrName: "", attrVal: "", attrValId: 0, clasId: 0, inputType: "",};
					obj['attrId'] = element['id'];
					obj['attrValId'] = 0;
					obj['attrVal'] = '';
					obj['attrName'] = element['attrName'];
					obj['inputType'] = element['inputType'];
					obj['clasId'] = classifyId.value;
					if(element['inputType'] === "11010002") {
						var child = [];
						if(null != element['productAttributeValues']) {
						element['productAttributeValues'].forEach((subElement) => {
							var obj = { attrId: 0, attrName: "", strAttrVal: "", attrVal: "", attrValId: 0, clasId: 0, inputType: "",};
							obj['attrId'] = element['id'];
							obj['attrValId'] = subElement['id'];
							obj['strAttrVal'] = subElement['attrValue'];
							obj['attrVal'] = '';//subElement['attrValue'];
							obj['attrName'] = element['attrName'];
							obj['inputType'] = element['inputType'];
							obj['clasId'] = classifyId.value;
							child.push(obj);
						});
						}
						obj['child'] = child;
					} else {
						obj['child'] = [];
					}
					attrValueInput.value.push(obj);
				});
			});
		}
        // 提交
        const onSubmit = () => {
            let strPics = '';
            contentPicList.value.forEach((item) => {
                strPics = strPics + item.value +",";
            });
            productForm['contentPics'] = strPics;
			// 表单校验
			saveProductInfo(productForm).then((res) => {
			    if(res.code != 200) {
			        if(res.type == 0) {
			            ElMessage.warning(res.data.msg);
			        } else {
			            ElMessage.error(res.data.msg);
			        }
			    } else {
			        ElMessage.success(SUCCESS_ADDDATA_DIALOG_MESSAGE);
			        router.push("/products");
			    }
			});
        };
		// 商品图片处理 ========================================================================================= START
		// 主图上传 ========================================================================================= START
        let masterImageUrl = ref('');
        const VAvatar = reactive({});
        const func_loadVAvatarData = (v) => {
            if(v['state'] === 1) {
                masterImageUrl.vlaue = v['imgUrl'];
                productForm['urlPic'] = v['imgUrl'];
            }
        };
        // 主图上传 ========================================================================================= END
		// 扩展图片 ========================================================================================= START
		let contentPicList = ref([]);
		const func_handleContentPicsSuccess = (res, file) => {
            if(file.response.code != 200) {
                if(res.type == 0) {
                    ElMessage.warning(res.data.msg);
                } else {
                    ElMessage.error(res.data.msg);
                }
            } else {
                var uploadFile = URL.createObjectURL(file.raw);
                var imageUrl = file.response.data.imgUrl;
                contentPicList.value.push(imageUrl);
                productForm['contentPicList'] = contentPicList.value;
                ElMessage.success("上传成功");
            }
		};
        const func_handleContentPicPreview = (file) => {
            dialogImageUrl.value= file['url'];
            dialogImageVisible.value = true;
        }
        const func_handleContentPicRemove = (uploadFile, uploadFiles) => {
            console.log(uploadFile, uploadFiles);
        };
		// 扩展图片 ========================================================================================= END
		// 商品图片处理 ========================================================================================= END
		// 品牌业务插件处理 ========================================================================================= START
		const vBoardsVisible = ref(false);
		const func_loadvBoardsDict = () => {
			vBoardsVisible.value = true;
		};
		const func_loadvBoardsDictData = (v) => {
			productForm['productBoardId'] = v['dicCode'];
			productForm['productBoardName'] = v['dicName'];
			vBoardsVisible.value = false;
		};
		// 品牌业务插件处理 ========================================================================================= END
        // 重置
        const onReset = () => {
            productFormRef.value.resetFields();
        };
        // 业务数据监听
        watch(() => props.selectValue, (val) => {
			if(props.selectValue['load']){
				// classifyId.value = props.selectValue['thdCatalogInput'];
				let obj = [props.selectValue['fstCatalogInput'],props.selectValue['sndCatalogInput'],props.selectValue['thdCatalogInput']];
				productForm['productClassifyId'] = obj.join(",");
			}
        },{deep: true,immediate: true});
        return {
			// 系统变量 =========================================================================================
            formLabelWidth, productFormRules, productFormRef, productForm, attrValueInput, productAttributeList, productAttributeForm,
			fistDis, sndDis, classifyId, shipmentProvinceOptions, provinceOptionProps, provinceOptionVal,
			// 主业务调用方法 =========================================================================================
            onSubmit, onReset, onNext, func_loadClassifyAttribute, func_loadShipmentProvinceOptions, func_setShipmentProvince,
			// 图片文件处理 =========================================================================================
            masterImageUrl, VAvatar, func_loadVAvatarData,
			dialogImageUrl, dialogImageVisible, dialogImageWidth, fileList, func_handleContentPicPreview, func_handleContentPicRemove, func_handleContentPicsSuccess,
			// 品牌业务插件处理 =========================================================================================
			vBoardsVisible, func_loadvBoardsDict, func_loadvBoardsDictData,
        };
    },
};
</script>
<style scoped>
.box-card {
	width:300px;
}
</style>